package com.czx.controller;

import com.czx.common.utils.R;
import com.czx.dto.PostDto;
import com.czx.entity.DiscussPost;
import com.czx.entity.User;
import com.czx.service.CommentService;
import com.czx.service.DiscussPostService;
import com.czx.service.LikeService;
import com.czx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/sys/post")
public class sysPostController {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @GetMapping("/list")
    public List<PostDto> postDtoList(){
        //创建一个集合接收数据
        List<PostDto> postDtos=new ArrayList<>();
        //查询所有的帖子
        List<DiscussPost> postList = discussPostService.list();
        //遍历
        for (DiscussPost discussPost : postList) {
            //查询点赞数量
            Long likeCount = likeService.getLikeCount(1, discussPost.getId());
            //查询评论数量
            Long commentCount = commentService.getCommentCountByPostId(discussPost.getId());
            //查询作者
            User user = userService.getById(discussPost.getUserId());
            PostDto postDto=new PostDto();
            postDto.setId(discussPost.getId());
            postDto.setTitle(discussPost.getTitle());
            postDto.setUsername(user.getUsername());
            postDto.setLikeCount(likeCount);
            postDto.setCommentCount(commentCount);
            //把获取的数据存入集合中
            postDtos.add(postDto);

        }
        return postDtos;

    }
    /**
     * 修改
     */
   @PutMapping("/update")
    public R update(@RequestBody PostDto postDto){
       //通过帖子id先查询
       DiscussPost discussPost = discussPostService.getById(postDto.getId());
      //获取postDto里的值
       User user = userService.getUserByUsername(postDto.getUsername());
       if (user==null){
           return R.fail("修改的作者不存在");
       }
       discussPost.setUserId(user.getId());
       discussPost.setTitle(postDto.getTitle());
       //修改
       boolean b = discussPostService.updateById(discussPost);
       if (b){
           return R.success("修改成功");
       }

       return R.fail("修改失败");
   }

}
